package com.kitchen.ui.deco
{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	
	
	internal class DecoItem extends Sprite
	{
		public var id:int=0;
		public var data:Object;
		private var isEdit:Boolean = false;
		private var range:Rectangle;
		private var timer:Timer = null;
		
		public function DecoItem(deco:Object, rec:Rectangle)
		{
			super();
			this.x = deco.nPx;
			this.y = deco.nPy;
			this.id = deco.id;
			this.data = deco;
			this.data.nEdit = 0;
			this.range = rec;
			this.layout(deco);
			this.addEventListener(MouseEvent.MOUSE_DOWN, downHandler);
			this.addEventListener(MouseEvent.MOUSE_UP, upHandler);
		}
		
		private function layout(deco:Object):void{
			var loader:Loader = new Loader();
			loader.load(new URLRequest(deco.sUrl));
			this.addChild(loader);
		}
		
		private function downHandler(mevent:MouseEvent):void{
			if(this.isEdit === true){
				this.startDrag();
			}
		}
		
		private function upHandler(mevent:MouseEvent):void{
			if(this.isEdit === true){
				this.stopDrag();
				if(((this.x >= this.range.x) && (this.x < this.range.width)) && ((this.y>= this.range.y) && (this.y < this.height))){
					this.data.nPx = this.x;
					this.data.nPy = this.y;
				}else{
					if(this.x > this.range.width){
						this.data.nPx = this.range.width-100;
					}else if(this.x < this.range.x){
						this.data.nPx = this.range.x;
					}else{
						this.data.nPx = this.x;
					}
					if(this.y > this.range.height){
						this.data.nPy = this.range.height-100;
					}else if(this.y < this.range.y){
						this.data.nPy = this.range.y;
					}else{
						this.data.nPy = this.y;
					}
					this.getTimer().start();
				}
				this.data.nEdit = 1;
			}
		}
		
		public function setEdit(edit:Boolean):void{
			if(edit === true){
				this.useHandCursor = true;
				this.buttonMode = true;
				this.isEdit = true;
			}else{
				this.buttonMode = false;
				this.useHandCursor = false;
				this.isEdit = false;
			}
		}
		
		private function getTimer():Timer{
			if(this.timer == null){
				this.timer = new Timer(50);
				this.timer.addEventListener(TimerEvent.TIMER, timerHandler);
			}
			return this.timer;
		}
		
		private function timerHandler(event:TimerEvent):void{
			if((this.x != this.data.nPx) || (this.y != this.data.nPy)){
				if(Math.abs(this.x - this.data.nPx) > 10){
					this.x = Math.floor((this.x + this.data.nPx)/2);
				}else{
					this.x = this.data.nPx;
				}
				if(Math.abs(this.y - this.data.nPy) > 10){
					this.y = Math.floor((this.y+this.data.nPy)/2);
				}else{
					this.y = this.data.nPy;
				}
			}else{
				this.timer.stop();
			}
		}
	}
}